package club.janna.springboot.study.processor;

import club.janna.springboot.study.service.JannaService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JannaBeanProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof JannaService) {
            return Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new JannaAopHandler(bean));
        }
        return null;
    }

    private static class JannaAopHandler implements InvocationHandler {
        private Object target;

        public JannaAopHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("janna aop handler before");
            Object result = method.invoke(target, args);
            System.out.println("janna aop handler after");
            return result;
        }
    }
}
